<script lang="ts" setup>
import { Component, RendererElement, RendererNode, VNode, computed, ref, watch } from 'vue'
import { Handle } from '@vue-flow/core'
import { convertFileSrc } from '@tauri-apps/api/core'
import { directive } from 'v-viewer'
import 'viewerjs/dist/viewer.css'
import { ArgumentItem } from '@/types/argument'

const VViewer = directive()

interface Props {
  label: string | object | VNode<RendererNode, RendererElement, {
    [key: string]: Any;
  }> | Component | undefined,
  id: string,
  inputs: (ArgumentItem & { active: boolean, value: Any })[],
  outputs: (ArgumentItem & { active: boolean, value: Any })[],
  selected?: boolean,
}
const props = defineProps<Props>()
const emit = defineEmits(['remove'])

const hiddenInpuRef = ref<HTMLInputElement>()
const input = computed(() => ({
  id: props.inputs[0].name,
  position: 'left',
  type: 'target',
  label: props.inputs[0].name,
  offset: 0,
  active: props.inputs[0].active,
  data: props.inputs[0].value || 0
} as Any))
const output = computed(() => ({
  id: props.outputs[0].name,
  position: 'right',
  type: 'source',
  label: props.outputs[0].name,
  offset: 0,
  active: props.outputs[0].active,
  data: props.outputs[0].value || 0
} as Any))
const data = ref({
  type: 'string',
  value: '' as Any
})

watch(() => props.selected, () => {
  if (props.selected) {
    hiddenInpuRef.value?.focus()
  }
})

function onKeyUp (evt: KeyboardEvent) {
  if (evt.code !== 'Delete') {
    return
  }
  emit('remove')
}

defineExpose({
  get code () {
    return `def fn_${props.id}(value):\n\treturn value`
  },
  focus () {
    hiddenInpuRef.value?.focus()
  },
  run ({ i }: { i: { type: string, value: Any } }) {
    data.value = i
    if (i.type === 'mat' && i.value) {
      data.value.value = convertFileSrc(i.value.replace('\\\\', '\\')) + '?v=' + Date.now()
    }
    return {
      o: i
    }
  }
})
</script>

<template>
  <div class="flow-node">
    <div class="header">
      <span class="label">{{ label }}</span>
    </div>
    <div class="workspace" :style="{ '--lines': 6 }">
      <div class="data-viewer text" v-if="data.type=='string' || data.type=='number' || data.type=='bool'">
        {{ data.value }}
      </div>
      <div class="data-viewer mat" v-else-if="data.type=='mat'" v-viewer>
        <img :src="data.value" />
      </div>
      <div v-else class="data-viewer invalid">不支持此类型</div>
    </div>
    <!-- 输入参数 -->
    <Handle :id="input.id" :position="input.position"
      :style="{ '--offset': input.offset }" :class="{active: input.active}">
      <span class="handle-label" :class="{active: input.data !== undefined}">
        {{ input.label }}
      </span>
    </Handle>
    <!-- 输出参数 -->
    <Handle :id="output.id" :position="output.position" :connectable-end="false"
      :style="{ '--offset': output.offset }" :class="{active: output.active}">
      <span class="handle-label" :class="{active: output.data !== undefined}">
        {{ output.label }}
      </span>
    </Handle>
    <input ref="hiddenInpuRef" type="text" autofocus="true" @keyup="onKeyUp" />
  </div>
</template>

<style lang="less" scoped>
.flow-node {
  padding: 0;
  --border-color: #445961;
  border: 1px solid var(--border-color);
  border-top-color: #445961;
  font-size: 12px;
  background: #303c3f;
  border-bottom-left-radius: 3px;
  border-bottom-right-radius: 3px;

  .header {
    background: #303c3f;
    padding: 5px 8px;
    display: flex;
    align-items: center;
    border-top: 1px solid var(--border-color);
    border-left: 1px solid var(--border-color);
    border-right: 1px solid var(--border-color);
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    position: absolute;
    bottom: 100%;
    left: 0;
    right: 0;

    .label {
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }

  .workspace {
    min-width: 60px;
    padding-top: 32px;
    min-height: 56px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    overflow: hidden;
    .data-viewer {
      flex-grow: 1;
      overflow: hidden;
      max-height: 240px;
      &.text {
        padding: 5px;
        width: 120px;
        background: #00000050;
        white-space: wrap;
        word-break: break-all;
        overflow-y: overlay;
      }
      &.mat {
        width: 120px;
        height: 120px;
        background: #00000030;
        display: flex;
        align-items: center;
        justify-content: center;
        img {
          max-width: 100%;
          max-height: 100%;
        }
      }
      &.invalid {
        max-height: 24px;
        opacity: 0.75;
        padding: 0 8px;
      }
    }
  }

  input {
    opacity: 0;
    position: absolute;
    left: -1000px;
  }
}

.vue-flow__handle {
  transition: all 0.175s 0.25s;
  width: 4px;
  height: 4px;
  top: 18px;
  display: flex;
  align-items: center;

  .handle-label {
    position: absolute;
    white-space: nowrap;
  }

  &.vue-flow__handle-left {
    transform: translate(-50%, calc(18px * var(--offset) - 50%));

    .handle-label {
      left: 12px;
    }

    &.active {
      background-color: #3F3;
    }
  }

  &.vue-flow__handle-right {
    transform: translate(50%, calc(18px * var(--offset) - 50%));

    .handle-label {
      right: 12px;
      &.active {
        color: #3FF;
      }
    }

    &.active {
      background-color: #3FF;
    }
  }

  &:hover {
    transition: all 0.175s 0s;
    border-color: var(--el-border-color);
    background-color: var(--el-color-primary);
  }
}
</style>
<style>
.vue-flow__node.vue-flow__node-debug.selected .flow-node {
  --border-color: #63e2b7;
}
</style>
